package com.hui.account.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.hui.account.R;
import com.hui.account.database.SQLManage;
import com.hui.account.entity.UserEntity;
import com.hui.account.utils.ButtonUtils;
import com.hui.account.utils.CommonUtils;
import com.hui.account.utils.ToastUtils;

/**
 * 新增用户
 */
public class UserAddActivity extends AppCompatActivity implements View.OnClickListener {

    Button backBtn, saveBtn;

    EditText userNameEdit, phoneEdit, remarkEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_add);

        // 1、设置屏幕顶部字体颜色
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        // 2、初始化页面
        initView();
    }

    /**
     * 初始化页面
     */
    private void initView() {
        backBtn = findViewById(R.id.user_add_back);
        saveBtn = findViewById(R.id.user_add_save);
        userNameEdit = findViewById(R.id.user_add_name);
        phoneEdit = findViewById(R.id.user_add_phone);
        remarkEdit = findViewById(R.id.user_add_remark);

        backBtn.setOnClickListener(this);
        saveBtn.setOnClickListener(this);
    }

    /**
     * 添加客户
     */
    private void addUser() {
        String userName = userNameEdit.getText().toString().trim();
        if (TextUtils.isEmpty(userName)) {
            ToastUtils.error(this, "【必填项】请输入客户姓名！", Gravity.CENTER, 0, 120);
            return;
        }

        if (userName.contains(CommonUtils.SPLIT)) {
            ToastUtils.error(this, "不允许使用特殊字符【" + CommonUtils.SPLIT + "】", Gravity.CENTER, 0, 120);
            return;
        }

        UserEntity user = new UserEntity(userName, 0);

        String phone = phoneEdit.getText().toString().trim();
        if (!TextUtils.isEmpty(phone))
            user.setPhone(phone);

        String remark = remarkEdit.getText().toString().trim();
        if (!TextUtils.isEmpty(remark))
            user.setRemark(remark);

        if (null != SQLManage.getUserByName(userName)) {
            ToastUtils.error(this, "该客户已存在！", Gravity.CENTER, 0, 120);
            return;
        }

        // 添加客户
        SQLManage.addUser(user);
        ToastUtils.success(this, "添加成功", Gravity.CENTER, 0, 0);
        finish();
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_add_back:
                finish();
                break;
            case R.id.user_add_save:
                if (!ButtonUtils.isFastDoubleClick()) {
                    addUser();
                }
                break;
        }
    }
}